import axios from 'axios'
import Vue from 'vue'
import router from '@/router'
import { getToken, removeToken } from './token'
const request = axios.create({
  baseURL: 'http://geek.itheima.net'
})

Vue.prototype.$baseURL = request.defaults.baseURL

request.interceptors.request.use(config => {
  const token = getToken()
  if (token) {
    config.headers.Authorization = `Bearer ${getToken()}`
  }
  return config
},
error => {
  return Promise.reject(error)
})

request.interceptors.response.use(response => {
  // http状态码以 2 3开头走到这里 表示成功
  return response
}, error => {
  // http状态码以 4 5开头走到这里 表示失败
  if (error.response.status === 401) {
    removeToken()
    router.replace('/login')
  }
  return Promise.reject(error)
})
export default request
